package com.longy.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SafeRegexMatcher {
    public static boolean matchesWithTimeout(String regex, String input, long timeoutMillis) {
        // Java 9+ 支持
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(new TimeoutCharSequence(input, timeoutMillis));
        return matcher.matches();
    }

    static class TimeoutCharSequence implements CharSequence {
        private final CharSequence inner;
        private final long timeout;
        private final long startTime;

        public TimeoutCharSequence(CharSequence inner, long timeout) {
            this.inner = inner;
            this.timeout = timeout;
            this.startTime = System.currentTimeMillis();
        }

        @Override
        public int length() {
            return 0;
        }

        // 实现CharSequence方法，在每次访问时检查超时
        @Override public char charAt(int index) {
            if (System.currentTimeMillis() - startTime > timeout) {
                throw new RuntimeException("Regex processing timeout");
            }
            return inner.charAt(index);
        }

        @Override
        public CharSequence subSequence(int i, int i1) {
            return null;
        }

        // 其他必要方法...
    }
}
